package com.zjy.financialsystemjavafx.service;

import com.zjy.financialsystemjavafx.model.entity.Loan;
import com.zjy.financialsystemjavafx.util.DatabaseUtil;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 借贷服务层，负责借贷记录的增删改查及还款操作
 */
public class LoanService {
    private final DataSource dataSource;

    public LoanService() {
        this.dataSource = DatabaseUtil.getDataSource();
    }

    /**
     * 获取指定用户的所有借贷记录
     */
    public List<Loan> getLoans(int userId) throws Exception {
        String sql = "SELECT loan_id, loan_type, amount, interest_rate, start_date, due_date, contact_person, contact_info, status, description " +
                     "FROM loans WHERE user_id = ?";
        List<Loan> list = new ArrayList<>();
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Loan loan = new Loan(
                        rs.getInt("loan_id"),
                        rs.getString("loan_type"),
                        rs.getDouble("amount"),
                        rs.getDouble("interest_rate"),
                        rs.getDate("start_date").toLocalDate(),
                        rs.getDate("due_date").toLocalDate(),
                        rs.getString("contact_person"),
                        rs.getString("contact_info"),
                        rs.getString("status"),
                        rs.getString("description")
                    );
                    list.add(loan);
                }
            }
        }
        return list;
    }

    /**
     * 添加新的借贷记录
     */
    public boolean addLoan(int userId, String loanType, double amount, double interestRate,
                           LocalDate startDate, LocalDate dueDate,
                           String contactPerson, String contactInfo,
                           String status, String description) throws Exception {
        String sql = "INSERT INTO loans(user_id, loan_type, amount, interest_rate, start_date, due_date, contact_person, contact_info, status, description) " +
                     "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ps.setString(2, loanType);
            ps.setDouble(3, amount);
            ps.setDouble(4, interestRate);
            ps.setDate(5, java.sql.Date.valueOf(startDate));
            ps.setDate(6, java.sql.Date.valueOf(dueDate));
            ps.setString(7, contactPerson);
            ps.setString(8, contactInfo);
            ps.setString(9, status);
            ps.setString(10, description);
            return ps.executeUpdate() > 0;
        }
    }

    /**
     * 更新借贷记录
     */
    public boolean updateLoan(Loan loan) throws Exception {
        String sql = "UPDATE loans SET loan_type=?, amount=?, interest_rate=?, start_date=?, due_date=?, contact_person=?, contact_info=?, status=?, description=? WHERE loan_id=?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, loan.getLoanType());
            ps.setDouble(2, loan.getAmount());
            ps.setDouble(3, loan.getInterestRate());
            ps.setDate(4, java.sql.Date.valueOf(loan.getStartDate()));
            ps.setDate(5, java.sql.Date.valueOf(loan.getDueDate()));
            ps.setString(6, loan.getContactPerson());
            ps.setString(7, loan.getContactInfo());
            ps.setString(8, loan.getStatus());
            ps.setString(9, loan.getDescription());
            ps.setInt(10, loan.getLoanId());
            return ps.executeUpdate() > 0;
        }
    }

    /**
     * 删除借贷记录
     */
    public boolean deleteLoan(int loanId) throws Exception {
        String sql = "DELETE FROM loans WHERE loan_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, loanId);
            return ps.executeUpdate() > 0;
        }
    }

    /**
     * 添加还款记录
     */
    public boolean addRepayment(int loanId, double amount, LocalDate date, String description) throws Exception {
        String sql = "INSERT INTO loan_repayments(loan_id, repayment_amount, repayment_date, description) VALUES (?, ?, ?, ?)";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, loanId);
            ps.setDouble(2, amount);
            ps.setDate(3, java.sql.Date.valueOf(date));
            ps.setString(4, description);
            return ps.executeUpdate() > 0;
        }
    }
} 